<script setup lang="ts">
import { useRequest } from "alova/client";
import DOMPurify from "dompurify";
import { useRoute } from "vue-router";

import type { ArticleDetailVO, CommentEntity } from "@/api/globals";
import { useUserStore } from "@/stores/user";

const route = useRoute();
const userStore = useUserStore();

// const article = ref<ArticleDetail | null>(null);
// const loading = ref(true);

// 模拟 API 请求
// const fetchArticle = async (id: number) => {
//     try {
//         // const res = await getArticleDetail(id)
//         // article.value = res.data

//         // 模拟数据（与你提供的一致）
//         article.value = {
//             id: 1,
//             title: "如何高效学习编程？这 5 个方法你一定要知道",
//             content:
//                 "<p>在当今数字化时代，编程已成为一项核心技能。本文将分享五种高效学习编程的方法...</p><p>方法一：刻意练习；方法二：项目驱动；方法三：善用社区...</p>",
//             excerpt: "掌握高效学习方法，让你的编程之路事半功倍。",
//             coverImage: "https://picsum.photos/800/400?random=1",
//             author: "李明",
//             categoryId: 1,
//             views: 1240,
//             createdAt: "2025-10-28T02:35:09.000Z",
//             updatedAt: "2025-10-28T02:35:09.000Z",
//             isDeleted: false,
//             deletedAt: null,
//             Category: { id: 1, name: "推荐" },
//             Comments: [
//                 {
//                     id: 1,
//                     targetId: 1,
//                     userId: 0,
//                     parentId: 0,
//                     content: "笑死我了",
//                     status: true,
//                     createdAt: "2025-10-28T04:54:11.000Z",
//                     updatedAt: "2025-10-28T04:54:11.000Z",
//                     isDeleted: false,
//                     deletedAt: null
//                 },
//                 {
//                     id: 2,
//                     targetId: 1,
//                     userId: 0,
//                     parentId: 0,
//                     content: "写得真好！已收藏，准备实践。",
//                     status: true,
//                     createdAt: "2025-10-28T05:10:22.000Z",
//                     updatedAt: "2025-10-28T05:10:22.000Z",
//                     isDeleted: false,
//                     deletedAt: null
//                 }
//             ]
//         };
//     } catch (error) {
//         console.error("Failed to load article", error);
//     } finally {
//         loading.value = false;
//     }
// };

const { data, loading, onSuccess } = useRequest(() =>
    Apis.Article.findOne({ pathParams: { id: route.params.id as unknown as number } })
);

onSuccess(async () => {
    await Apis.Article.update({
        pathParams: {
            id: route.params.id as unknown as number
        },
        data: {
            views: article.value?.views + 1
        }
    });
});

const article = computed<ArticleDetailVO>(() => data.value?.data);

// 过滤有效评论（审核通过 + 未删除）
const validComments = computed(() => {
    return article.value?.Comments.filter(c => c.status && !c.isDeleted) || [];
});
// 格式化时间
const formatTime = (dateStr: string): string => {
    const date = new Date(dateStr);
    return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit"
    });
};

// 格式化时间（用于评论）
const formatCommentTime = (dateStr: string): string => {
    const now = new Date();
    const past = new Date(dateStr);
    const diffMs = now.getTime() - past.getTime();
    const diffMin = Math.floor(diffMs / (1000 * 60));
    const diffHour = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDay = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffMin < 1) return "刚刚";
    if (diffMin < 60) return `${diffMin}分钟前`;
    if (diffHour < 24) return `${diffHour}小时前`;
    if (diffDay < 7) return `${diffDay}天前`;
    return past.toLocaleDateString("zh-CN");
};

// 格式化阅读量
const formatViews = (views: number): string => {
    if (views >= 10000) return (views / 10000).toFixed(1) + "万";
    return views.toString();
};

// 安全渲染 HTML
const sanitizeHTML = (html: string): string => {
    return DOMPurify.sanitize(html);
};

// 发表评论成功
const handleCommentArticle = (comment: CommentEntity) => {
    const commentsVO = {
        ...comment,
        User: {
            id: userStore.userinfo.id,
            username: userStore.userinfo.username,
            nickname: userStore.userinfo.nickname,
            avatar: userStore.userinfo.avatar
        }
    };
    article.value.Comments.push(commentsVO);
};

// onMounted(() => {
//     const id = Number(route.params.id);
//     if (id) {
//         console.log("id", id);
//         // fetchArticle(id);
//         send();
//     }
// });
</script>

<template>
    <div class="mx-auto max-w-4xl px-4 py-6">
        <div v-if="loading" class="py-20 text-center">
            <p class="text-gray-500">加载中...</p>
        </div>

        <article v-else-if="article" class="mb-10 overflow-hidden rounded-lg bg-white shadow-sm">
            <!-- 封面图 -->
            <img
                v-if="article.coverImage"
                :src="article.coverImage"
                :alt="article.title"
                class="h-64 w-full object-cover"
            />

            <!-- 内容区 -->
            <div class="p-6">
                <!-- 分类标签 -->
                <div class="mb-4">
                    <span class="inline-block rounded-full bg-blue-100 px-3 py-1 text-xs font-semibold text-blue-800">
                        {{ article.Category.name }}
                    </span>
                </div>

                <!-- 标题 -->
                <h1 class="mb-4 text-3xl font-bold leading-tight text-gray-900">
                    {{ article.title }}
                </h1>

                <!-- 元信息 -->
                <div class="mb-6 flex flex-wrap items-center gap-2 text-sm text-gray-500">
                    <span>{{ article.author }}</span>
                    <span>•</span>
                    <span>{{ formatTime(article.createdAt) }}</span>
                    <span>•</span>
                    <span>{{ formatViews(article.views) }} 阅读</span>
                </div>

                <!-- 正文内容（安全渲染） -->
                <div class="prose prose-gray max-w-none" v-html="sanitizeHTML(article.content)"></div>
            </div>
        </article>

        <a-divider style="height: 2px; background-color: #eee" />

        <comments-reply-comment :target-id="article?.id" @submit-success="handleCommentArticle" />

        <!-- 评论区 -->
        <div v-if="article && article.Comments.length > 0" class="mt-12">
            <h2 class="mb-4 text-xl font-bold text-gray-900">评论（{{ article.Comments.length }}）</h2>
            <!-- <div class="space-y-6">
                <template v-for="comment in article.Comments">
                    <div
                        v-if="comment.status && !comment.isDeleted"
                        :key="comment.id"
                        class="rounded-lg bg-gray-50 p-4"
                    >
                        <div class="mb-2 text-gray-800">{{ comment.content }}</div>
                        <div class="text-xs text-gray-500">
                            {{ formatTime(comment.createdAt) }}
                        </div>
                    </div>
                </template>
            </div> -->

            <a-comment
                v-for="comment in validComments"
                :key="comment.id"
                :author="`${comment.User.nickname || comment.User.username || '匿名'}`"
                :datetime="formatCommentTime(comment.createdAt)"
            >
                <template #content>
                    <p>{{ comment.content }}</p>
                </template>

                <!-- 头像（可自定义） -->
                <template #avatar>
                    <a-avatar :size="32" :style="{ backgroundColor: '#1890ff' }" :src="comment.User.avatar">
                        {{ comment.userId ? `U${String(comment.userId).slice(-2)}` : "客" }}
                    </a-avatar>
                </template>

                <!-- 操作区（可选：回复按钮） -->
                <!--                 
        <template #actions>
          <span key="comment-basic-reply-to">回复</span>
        </template> -->
            </a-comment>

            <!-- <comments-comment-list /> -->
        </div>

        <!-- 无评论提示 -->
        <div v-else-if="article" class="mt-12 text-center text-gray-500">还没有评论，快来抢沙发吧！</div>
    </div>
</template>

<style scoped>
/* 可选：增强 prose 样式（Tailwind Typography 插件效果） */
.prose :where(p):not(:where([class~="not-prose"] *)) {
    margin-top: 1em;
    margin-bottom: 1em;
    line-height: 1.75;
}
.prose :where(h2):not(:where([class~="not-prose"] *)) {
    margin-top: 2em;
    margin-bottom: 1em;
    font-size: 1.5em;
    font-weight: 600;
}
</style>
